#!/bin/sh
### BEGIN INIT INFO
# Provides:          natapp.cn
# Required-Start:    $network $remote_fs $local_fs
# Required-Stop:     $network $remote_fs $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: autostartup of natapp for RaspberryPi
### END INIT INFO


eval `dbus export natapp_`
source /koolshare/scripts/base.sh


natapp_pid=`ps | grep "/koolshare/bin/natapp" | grep -v 'grep' | awk '{print $1}'`

start_natapp(){
	echo "$natapp_pid"
	if [ -n "$natapp_pid" ]; then
		echo "运行"
	else
		echo "没运行"
	fi

	
    nat_auto_start
    wan_auto_start
    if [[ "$natapp_authtoken" == "" ]] && [[ "$natapp_clienttoken" == "" ]];then
    	dbus set natapp_last_status="<font color=red>请填写隧道信息</font>"
    	echo '请填写隧道信息'
    		logger "[natapp]: 请填写隧道信息"
    else
    	if [ -f "/koolshare/bin/natapp.log" ]; then
    		rm /koolshare/bin/natapp.log
    	fi
	    start-stop-daemon -S -m -b -p /var/run/soft_natapp.pid -x /koolshare/bin/natapp -- --authtoken=$natapp_authtoken --clienttoken=$natapp_clienttoken --log=/koolshare/bin/natapp.log --loglevel=INFO || true
		if [ -n "$natapp_pid" ]; then
	    	dbus set natapp_last_status="<font color=red>启动失败，请检查参数</font>"
    		echo '启动失败，请检查参数'
    		logger "[natapp]: 启动失败，请检查参数问题"
	    else
		    dbus set natapp_last_status="<font color=green>服务已启动</font>"
		    dbus set natapp_last_act=$(date +%Y-%m-%d)' '$(date +%H:%M:%S)
		    echo '服务已启动'
    		logger "[natapp]: 服务已启动"
	    fi
    fi
    echo 
}

stop_natapp(){
    dbus remove __event__onnatstart_natapp
    dbus remove __event__onwanstart_natapp
    if [ -f "/koolshare/bin/natapp.log" ]; then
    	rm /koolshare/bin/natapp.log
    fi
    if [ -n "$natapp_pid" ]; then
    	start-stop-daemon -K -p /var/run/soft_natapp.pid || true
    fi
    dbus set natapp_last_status="<font color=red>服务未开启</font>"
}


nat_auto_start(){
	dbus set __event__onnatstart_natapp="/koolshare/scripts/natapp_config.sh"
}

wan_auto_start(){
	dbus set __event__onwanstart_natapp="/koolshare/scripts/natapp_config.sh"
}

case $ACTION in
start)
	if [ "$natapp_enable" == "1" ];then
		echo "启动natapp！"
    	logger "[natapp]: 启动natapp！"
		start_natapp
	else
		echo "natapp未设置启动，跳过！"
    	logger "[natapp]: natapp未设置启动，跳过！"
	fi
	;;
stop | kill )
		echo "停止natapp！"
    	logger "[natapp]: 停止natapp！"
	stop_natapp
	;;
restart)
	stop_natapp
	start_natapp
	;;
*)
	echo "Usage: $0 (start|stop|restart)"
	exit 1
	;;
esac